package com.smart.buss.ctrl;

import com.alibaba.fastjson.JSON;
import com.smart.buss.service.*;
import com.smart.buss.vo.*;
import com.smart.primary.common.common.BaseCtrl;
import com.smart.primary.common.common.Constants;
import com.smart.primary.common.util.AjaxResult;
import com.smart.primary.common.util.DateUtil;
import com.smart.primary.common.util.RedisUtils;
import com.smart.primary.common.util.Util;
import com.smart.primary.util.HideDataUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletContext;
import java.util.*;

@RestController
@RequestMapping("/buss/daka/log")
public class BussDakaLogController extends BaseCtrl {
	private final static Logger logger= Logger.getLogger(BussDakaLogController.class);
	@Autowired
	private BussDakaService bussDakaService;
	@Autowired
	private BussDakaLogService bussDakaLogService;
	@Autowired
	private BussAccountLogService bussAccountLogService;
	@Autowired
	private BussUserService bussUserService;
	@Autowired
	private BussSetService bussSetService;
	@Autowired
	private BussCodeService bussCodeService;

	@RequestMapping
	public AjaxResult getList(BussDakaLog entity) throws Exception{
		List<BussDakaLog> list=bussDakaLogService.queryListByPage(entity);
		return getResult(entity, list);
	}

	/**
	 * 累计打卡
	 */
	@RequestMapping("/addup")
	public AjaxResult addup(BussDakaLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.success(new ArrayList<>());
		}
		entity.setDakaStatus(2);//已领取的
		List<BussDakaLog> list=bussDakaLogService.queryList(entity);
		Integer price=0;
		for (BussDakaLog log: list) {
			price+=log.getPaifaPrice();
		}
		entity.setDakaStatus(null);
		int zongnum=bussDakaLogService.queryCount(entity);
		Map m=new HashMap();
		m.put("price",price/100);
		m.put("sucnum",list.size());
		m.put("zongnum",zongnum);
		return AjaxResult.success(m);
	}


	/**
	 * 上期打卡金额
	 */
	@RequestMapping("/yset")
	public AjaxResult yset() throws Exception{
		BussDakaLog entity=new BussDakaLog();
		String qihao=DateUtil.changeDateTOStr(DateUtil.addDay(-2)); //昨天开奖的
		entity.setDakaId(qihao);
		entity.setField("create_date");
		entity.setOrder("asc");
		List<BussDakaLog> list=bussDakaLogService.queryList(entity);

		String zaoname="暂无";
		String zaodesc="暂无";
		if(list!=null && list.size()>0){
			BussDakaLog zao=list.get(0);
			zaoname=zao.getUserId();
			zaodesc=DateUtil.changeDateTOTime(zao.getCreateDate())+" 打卡";
		}

		BussDakaLog zuidu=bussDakaLogService.getZuiDuo();
		String zuiname="暂无";
		String zuidesc="暂无";
		if(zuidu!=null){
			Integer cishu=zuidu.getDakaPrice()==null?0:zuidu.getDakaPrice();
			zuiname=zuidu.getUserId();
			zuidesc="连续打卡"+cishu+"天";
		}

		Integer price=0;
		Integer sucman=0;
		Integer shiman=0;
		String maximum="暂无";
		String name="暂无";
		Integer zuiduo=0;
		for (BussDakaLog log: list) {
			if(log.getDakaStatus()==2){ // 已领取的
				price+=log.getPaifaPrice();  // 总金额
				sucman++;
			}else {
				shiman++;
			}
			if(zuiduo<log.getPaifaPrice()){
				maximum="瓜分"+log.getPaifaPrice()/100.0+"元";
				name=log.getUserId();
			}
		}
		Map m=new HashMap();
		Map m0=new HashMap();
		m0.put("price",price/100.0); // 上期瓜分金额
		m0.put("sucman",sucman); // 成功人数
		m0.put("shiman",shiman); // 失败人数

		Map m1=new HashMap();
		m1.put("name", HideDataUtil.hidePhoneNo(name)); //  教皇附体
		m1.put("desc",maximum); //  教皇附体

		Map m2=new HashMap();
		m2.put("name",HideDataUtil.hidePhoneNo(zuiname)); //  劳动模范
		m2.put("desc",zuidesc); //  劳动模范

		Map m3=new HashMap();
		m3.put("name",HideDataUtil.hidePhoneNo(zaoname)); //  起的最早
		m3.put("desc",zaodesc); //  起的最早

		m.put("shangqi",m0);
		m.put("jiaohuang",m1);
		m.put("laodong",m2);
		m.put("zuizao",m3);

		return AjaxResult.success(m);
	}

	/**
	 *  打卡总人数 总金额  第多少期
	 */
	//http://localhost:8080/task/buss/daka/log/benqi?userId=12345678910
	@RequestMapping("/benqi")
	public AjaxResult benqi(BussDakaLog log) throws Exception{

		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			log.setUserId(phone);
		}
		if(RedisUtils.getJedis()==null){
			return AjaxResult.failure();
		}


		BussDaka bussDaka=new BussDaka();
		bussDaka.setStatus(0);
		bussDaka=bussDakaService.queryObject(bussDaka);
		// 获取 是否有奖金
		Boolean bool=false;

		BussDaka upBussDaka=new BussDaka();
		upBussDaka.setIssueNumber(bussDaka.getUpIssueNumber());
		upBussDaka=bussDakaService.queryObject(bussDaka);
		
		if(StringUtils.isNotBlank(log.getUserId())){
			log.setDakaStatus(1);
			log.setDakaId(bussDaka.getUpIssueNumber());
			BussDakaLog query=bussDakaLogService.queryObject(log);
			if(query!=null){
				bool=true;
			}
		}
		BussDaka entity = new BussDaka();
		entity.setStatus(0);
		BussDaka query = bussDakaService.queryObject(entity);

		String kaijiang="领奖时间 ";
		if(query!=null){
			kaijiang+=dateToString2(query.getCloseTime())+" - ";
		}
		BussSet set=bussSetService.queryObject(null);

		if(set!=null && StringUtils.isNotBlank(set.getDaoqi()) && set.getDaoqi().length()>3){
			kaijiang+=set.getDaoqi().substring(0,set.getDaoqi().length()-3);
		}

		int aiqiyiupSuccessNum=0;
		int aiqiyiupall=0;

		BussDaka bdaka=new BussDaka();
		bdaka.setStatus(0);
		BussDaka querydaka=bussDakaService.queryObject(bdaka);
		if(querydaka!=null && StringUtils.isNotBlank(querydaka.getUpIssueNumber())){
			BussDakaLog qdakaLog=new BussDakaLog();
			qdakaLog.setDakaId(querydaka.getUpIssueNumber());
			List<BussDakaLog> qlist=bussDakaLogService.queryList(qdakaLog);
			aiqiyiupall=qlist.size();
			for (BussDakaLog dk: qlist) {
				if(dk.getDakaStatus() !=null && dk.getDakaStatus()==2 && StringUtils.isNotBlank(dk.getRemarks())){
					aiqiyiupSuccessNum++;
				}
			}
		}

		Map m=new HashMap(); 
		m.put("kaijiang",kaijiang);
		m.put("jiangjin",bool);
		m.put("zongPrice", bussDaka.getZongPrice());
		m.put("zongNum", bussDaka.getZongNum());
		m.put("benqi", bussDaka.getQihao());
		m.put("upJiangPrice", upBussDaka.getJiangPrice());
		m.put("upErrorNum", upBussDaka.getErrorNum());
		m.put("upSuccessNum", upBussDaka.getSuccessNum());
		m.put("aiqiyiupErrorNum",aiqiyiupall-aiqiyiupSuccessNum);
		m.put("aiqiyiupSuccessNum", aiqiyiupSuccessNum);
		return AjaxResult.success(m);
	}

	///http://localhost:8080/task/buss/daka/log/list?userId=12345678910
	@RequestMapping("/list")
	public AjaxResult list(BussDakaLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.success(new ArrayList<>());
		}
		entity.setDakaStatus(2);//已领取的
		entity.setField("create_date");
		entity.setOrder("DESC");
		return AjaxResult.success(bussDakaLogService.queryListByPage(entity));
	}
	/**
	 * 获取打卡信息
	 */
//	http://localhost:8080/task/buss/daka/log/info?userId=12345678910
	@RequestMapping("/info")
	public AjaxResult listinfo(BussDakaLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.failure("参数不足");
		}
		entity.setDakaId(DateUtil.getNowDate());
		return AjaxResult.success(bussDakaLogService.queryObject(entity));
	}

	/**
	 * 领取打卡金
	 */
	//	http://ts.timxu.me:8080/task/buss/daka/log/get
	@Transactional
	@RequestMapping("/get")
	public AjaxResult get(BussDakaLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.failure("参数不足");
		}


		BussDaka bdaka=new BussDaka();
		bdaka.setStatus(0);
		BussDaka querydaka=bussDakaService.queryObject(bdaka);
		if(querydaka==null || StringUtils.isBlank(querydaka.getUpIssueNumber())){
			return AjaxResult.failure("期数错误");
		}
		//获取前一天的打卡编号
		entity.setDakaId(querydaka.getUpIssueNumber());
		BussDakaLog query=bussDakaLogService.queryObject(entity);
		if(query==null){
			return AjaxResult.failure("上期未打卡");
		}
        if(query.getDakaStatus()==2){
            return AjaxResult.failure("已领取");
        }
        /**
         *  领取超时 勿删
         */
        if(query.getDakaStatus()==3){
            return AjaxResult.failure("领取超时");
        }
		// 设置打卡日志状态为领取
		BussSet set=bussSetService.queryObject(null);
		Date dd=DateUtil.stringToDate(DateUtil.getNowDate()+set.getDaoqi(),"yyyy-MM-ddHH:mm:ss");

		if(System.currentTimeMillis()>dd.getTime()){
            query.setDakaStatus(3);
		}else {
            query.setDakaStatus(2);
		}
        /**
         *  领取超时 勿删
         */
		bussDakaLogService.update(query);
		if(query.getDakaStatus()==3){

			// 如果是打卡领东西  超时 设置激活码 为未使用
			if(query.getType()!=null && query.getType()==1){
				if(StringUtils.isNotBlank(query.getRemarks())){
					BussCode code=new BussCode();
					code.setCode(query.getRemarks());
					try {
						code=bussCodeService.queryObject(code);
						if(code!=null){
							code.setIsuse(0);
							code.setUserId("");
							bussCodeService.update(code);
						}
					}catch (Exception e){
						logger.info("激活码恢复错误");
					}
				}
			}

            return AjaxResult.failure("领取超时");
        }
		Map m=new HashMap();

		if(query.getType()!=null && query.getType()==1){
			if(query.getDakaStatus()!=null && query.getDakaStatus()==0){
				m.put("value","");
				m.put("type",3);
				return AjaxResult.success(m);
			}
			if(StringUtils.isNotBlank(query.getRemarks())){
				BussAccountLog flog=new BussAccountLog();
				flog.setId(Util.getUUID());
				flog.setUserId(entity.getUserId());
				flog.setTaskId(query.getId());
				flog.setAddSub(1);
				flog.setPrice(0.0);
				flog.setLogtype(2);
				flog.setRemarks("打卡中爱奇艺会员 激活码："+ query.getRemarks());
				bussAccountLogService.insert(flog);

				m.put("value",query.getRemarks());
				m.put("type",1);
			}else {

				m.put("value","");
				m.put("type",2);
			}
			return AjaxResult.success(m);
		}

		// 设置日志
		Double dou=query.getPaifaPrice().doubleValue()/100.0;
		BussAccountLog flog=new BussAccountLog();
		flog.setId(Util.getUUID());
		flog.setUserId(entity.getUserId());
		flog.setTaskId(query.getId());
		flog.setAddSub(1);
		flog.setPrice(dou);
		flog.setLogtype(2);
		flog.setRemarks("打卡奖励");
		bussAccountLogService.insert(flog);
		// 设置用户账户金
		BussUser user=new BussUser();
		user.setId(entity.getUserId());
		BussUser quser=bussUserService.queryObject(user);
		quser.setAccount(quser.getAccount()+dou);
		bussUserService.update(quser);
		m.put("value",dou);
		m.put("type",0);
		return AjaxResult.success(m);
	}
	//	http://localhost:8080/task/buss/daka/log/save?userId=12345678910&dakaPrice=20
	@Transactional
	@RequestMapping("/save")
	public AjaxResult save(BussDakaLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getUserId()) || entity.getDakaPrice()==null || entity.getDakaPrice()<=0){
			return AjaxResult.failure("参数不足");
		}
		
		BussUser user=new BussUser();
		user.setId(entity.getUserId());
		BussUser quser=bussUserService.queryObject(user);
		if(quser.getAccount()<entity.getDakaPrice()){
			return AjaxResult.failure("余额不足");
		}
		

//
		BussDaka bussDaka=new BussDaka();
		bussDaka.setStatus(0);
		bussDaka=bussDakaService.queryObject(bussDaka);

		entity.setDakaId(bussDaka.getIssueNumber());
		BussDakaLog checkObj = bussDakaLogService.queryObject(entity);
		if(checkObj != null){
			return AjaxResult.failure("你已参与");
		}
		
		bussDaka.setZongPrice(entity.getDakaPrice());
		bussDaka.setZongNum(1);
		bussDakaService.updateLock(bussDaka);
		
		BussDakaLog newBussDaka = new BussDakaLog();
		String id=Util.getUUID();
		newBussDaka.setId(id);
		newBussDaka.setUserId(entity.getUserId());
		newBussDaka.setDakaId(bussDaka.getIssueNumber());
		newBussDaka.setDakaPrice(entity.getDakaPrice()*100); // s设置为分
		newBussDaka.setDakaStatus(0);
		bussDakaLogService.insert(newBussDaka);
		
		// 扣除账户金额
		Double dou=entity.getDakaPrice().doubleValue();
		quser.setAccount(quser.getAccount()-dou);
		bussUserService.update(quser);
		//账户日志
		BussAccountLog flog=new BussAccountLog();
		flog.setId(Util.getUUID());
		flog.setUserId(entity.getUserId());
		flog.setTaskId(id);
		flog.setAddSub(0);
		flog.setPrice(-dou);
		flog.setLogtype(2);
		flog.setRemarks("每日打卡");
		bussAccountLogService.insert(flog);
		return AjaxResult.saveSuccess();
	}
}
